var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数
var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载
var search_companyName=null;

$(function(){
	$("#searchButton").click(function(){
			search_companyName=$("#companyName").val();
			offset=0;
			initdata(false);
	});
	$(".query-jiant").click(function(){
		var src=$("#jiant").attr("src");
		if(src.indexOf("jiant2")>=0){
			$("#jiant").attr("src",ctx+"/assets/img/jiant.png");
			$(".choose").show(300);
		}else{
			$("#jiant").attr("src",ctx+"/assets/img/jiant2.png");
			$(".choose").hide(300);
		}
	});	

	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
	$(window).scroll(function () {
        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
        //$(window).height()获取当前窗体的高度
        //$(document).height()获取当前文档的高度
        var bot = 0; //bot是底部距离的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
        	if(pageLoading){
        		pageLoading=false;
        		offset+=limit;
        		initdata(true);
        	}
        }
    });
	
	initdata(false);
	
});

function initdata(isappend){
	$.ajax({
        url : ctx+'/advertisement/advertisementData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"companyName":search_companyName,
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	
        	var newcontent = '';
        	
        	var totalElements=result.totalElements;
        	
        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        			var statusColor="";
        			var mainButton="";
        			var selectButton="";
            			statusColor="btn-primary";
        				mainButton=
        					"<a href='#' data-id='"+data.id+"' linkAddress='"+data.linkAddress+"' sequence='"+data.sequence+"' picture='"+data.picture+"' class='btn btn-primary btn-xs updatethis updateAdvertisement'>编辑</a>";
        				
        				selectButton+="<li style='cursor:pointer;'><a href='#'  data-value='"+data.id+"'  class='btn-link deletethis'>删除</a></li>";
            		var allButton="<div class='btn-group'>"+
            							mainButton+
									  "<button type='button' class='btn "+statusColor+" btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>"+
									    "<span class='caret'></span>"+
									    "<span class='sr-only'>Toggle Dropdown</span>"+
									  "</button>"+
									  "<ul class='dropdown-menu' role='menu'>"+
									  	selectButton+
									  "</ul>"+
									"</div>";
            	
            	
	    newcontent+="<tr class='grid-data tr-hui'  >"+
						"<td>"+data.linkAddress+"</td>"+
						(isMainCompany?("<td>"+data.companyName+"</td>"):"")+
						"<td>"+data.sequence+"</td>"+
						"<td>"+allButton+"</td>"+
					"</tr>";
        		});
        	}
        	if(!isappend){
        		$("#advertisementTab .grid-data").remove();
        	}
        	$("#advertisementTab").append(newcontent);
        	$("#advertisementTab .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.page.content.length;
            			pageLoading=true;
            		}else{
            			pageLoading=false;
            		}
            	}
        	}
        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        	}else{
        		//滚动达到pagingLimit条开始显示分页
        		if(currentTotalElements==pagingLimit){
            		pageLoading=false;
            		hasShowPages=true;
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
            	}
        	}
        }
	});
}

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}